const path = require('node:path')
/**
 * 获取搜索事件str
 * @param codeConfig
 */
const getOnSearchStr = codeConfig => {
  const { listPageApiConfig } = codeConfig.apiConfigStates
  return `
    /** 搜索事件 */
    const onSearch = async () => {
      const res = await api.${listPageApiConfig.funcName}(store.query)
      if (res.success) {
        store.tableData = res.data.list
        store.total = res.data.total
      } else {
        store.tableData = []
        store.total = 0
      }
    }
  `
}

/**
 * 获取刷新列表函数str
 * @param codeConfig
 */
const getRefreshListHandlerStr = codeConfig => {
  const { hasRefreshListHandler } = codeConfig.apiConfigStates

  return hasRefreshListHandler ?
    `
    /**
     * @description 刷新列表
     * @param initPage 是否重置页码
     */
    const refreshListHandler = (initPage = false) => {
      store.listPageRef?.search(initPage)
    }
  ` :
    ''
}

/**
 * 获取删除操作函数str
 * @param codeConfig
 */
const getDelActionHandlerStr = codeConfig => {
  const { delApiConfig } = codeConfig.apiConfigStates
  // todo 应该更具类型去生成参数，暂时先写死为{id: id: row.${codeConfig.rowKey}!}
  const properties = delApiConfig?.request.schema.jsonSchema.properties

  return delApiConfig ?
    `
      /**
       * @description 删除操作
       * @param row 当前行
       */
      const delActionHandler = (row: TableRow) => {
        confirm(
          async () => {
            const res = await api.${delApiConfig.funcName}({
              id: row.${codeConfig.rowKey}!
            })
            if (res.success) {
              refreshListHandler()
            }
            return res.success
          }
        )
      }
    ` :
    ''
}

/**
 * 获取编辑操作函数str
 * @param codeConfig
 * @param utils
 */
const getEditActionHandlerStr = (codeConfig, utils) => {
  const { modifyApiConfig, listPageApiConfig } = codeConfig.apiConfigStates
  if (!modifyApiConfig) {
    return ''
  }

  const listVO =
    codeConfig.dataSchemasNameMap[utils.extractGenericType(listPageApiConfig.response.schema.name)]
  const rowProperties = listVO.jsonSchema.properties

  const modifyDataProperties = modifyApiConfig.request.schema.jsonSchema.properties

  const modifyDataStr = []

  // 在row中存在的属性进行默认值追加
  for (const key of Object.keys(modifyDataProperties)) {
    if (rowProperties[key]) {
      modifyDataStr.push(`${key}: row.${key}`)
    }
  }

  return `
    /**
     * @description 编辑操作
     * @param row 当前行
     */
    const editActionHandler = (row: TableRow) => {
      store.isModify = true
      // todo 须根据当前行数据设置编辑表单数据
      store.modifyData = { ${modifyDataStr.join(',\n')} }
      store.visibleDialogModify = true
    }
  `
}

/**
 * 获取新增事件str
 * @param codeConfig
 */
const getOnAddStr = codeConfig => {
  const { addApiConfig } = codeConfig.apiConfigStates
  return addApiConfig ?
    `
      /**
       * @description 编辑操作
       */
      const onAdd = () => {
        store.isModify = false
        store.modifyData = {}
        store.visibleDialogModify = true
      }
    ` :
    ''
}

/**
 * 新增编辑提交函数str
 * @param codeConfig
 */
const getModifySubmitHandlerStr = codeConfig => {
  const { hasModifyDialog, addApiConfig, modifyApiConfig } = codeConfig.apiConfigStates

  if (!hasModifyDialog) {
    return ''
  }
  let handlerStr = ''

  const getParams = properties => {
    const paramsStr = []
    for (const key of Object.keys(properties)) {
      paramsStr.push(`${key}: store.modifyData.${key}!`)
    }
    return paramsStr.join(',\n')
  }

  if (addApiConfig && modifyApiConfig) {
    handlerStr = `
      let res
      if (store.isModify) {
        // 编辑数据
        const updateParams: ${modifyApiConfig.request.schema.name} = {
          ${getParams(modifyApiConfig.request.schema.jsonSchema.properties)}
        }
        res = await api.${modifyApiConfig.funcName}(updateParams)
      } else {
        // 新增数据
        const addParams: ${addApiConfig.request.schema.name} = {
          ${getParams(addApiConfig.request.schema.jsonSchema.properties)}
        }
        res = await api.${addApiConfig.funcName}(addParams)
      }
    `
  } else if (addApiConfig) {
    handlerStr = `
      // 新增数据
      const addParams: ${addApiConfig.request.schema.name} = {
        ${getParams(addApiConfig.request.schema.jsonSchema.properties)}
      }
      const res = await api.${addApiConfig.funcName}(addParams)
    `
  } else if (modifyApiConfig) {
    handlerStr = `
      // 编辑数据
      const updateParams: ${modifyApiConfig.request.schema.name} = {
        ${getParams(modifyApiConfig.request.schema.jsonSchema.properties)}
      }
      const res = await api.${modifyApiConfig.funcName}(updateParams)
    `
  }

  return `
    /** 新增编辑提交事件 */
    const modifySubmitHandler = async () => {
      ${handlerStr}
      if (res.success) {
        store.visibleDialogModify = false
        refreshListHandler()
      }
    }`
}

/**
 * 获取导出事件str
 * @param codeConfig
 */
const getOnExportExcelStr = codeConfig => {
  const { exportExcelApiConfig } = codeConfig.apiConfigStates
  return exportExcelApiConfig ?
    `
      /** 导出按钮事件 */
      const onExportExcel = async () => {
        store.exportExcelLoading = true
        try {
          await api.${exportExcelApiConfig.funcName}(store.query)
        } finally {
          store.exportExcelLoading = false
        }
      }
    ` :
    ''
}

/**
 * 获取导出前事件str
 * @param {*} codeConfig 
 */
const getOnExportBeforeCreateStr = codeConfig => {
  const { exportExcelApiConfig } = codeConfig.apiConfigStates
  return exportExcelApiConfig ?
    `
      /** 进行导出前的方法 */
      const onExportBeforeCreate = async () => {
        if (store.tableData.length === 0) {
          return '无数据导出！'
        }
        return true
      }
    ` :
    ''
}

module.exports = (codeConfig, utils) => {
  const { delApiConfig, hasRowActions } = codeConfig.apiConfigStates

  const refreshListHandlerStr = getRefreshListHandlerStr(codeConfig)
  const onExportExcelStr = getOnExportExcelStr(codeConfig)
  const delActionHandlerStr = getDelActionHandlerStr(codeConfig)
  const editActionHandlerStr = getEditActionHandlerStr(codeConfig, utils)
  const onAddStr = getOnAddStr(codeConfig)
  const modifySubmitHandlerStr = getModifySubmitHandlerStr(codeConfig)
  const onExportBeforeCreateStr = getOnExportBeforeCreateStr(codeConfig)

  const code = `
    import * as api from '/@/api${codeConfig.apiFilePath}'
    ${delApiConfig ? 'import { confirm } from \'/@/hooks/confirm\'' : ''}
    import type { Store, ${hasRowActions ? 'TableRow' : ''} } from '../types'

    export const useHandler = (store: Store) => {

      ${getOnSearchStr(codeConfig)}

      ${refreshListHandlerStr}

      ${onExportExcelStr}

      ${delActionHandlerStr}
      
      ${editActionHandlerStr}

      ${onAddStr}

      ${modifySubmitHandlerStr}

      ${onExportBeforeCreateStr}

      /**
       * 表格选择change
       * @param selection 已选项
       */
      const onSelectionChange = (selection: TableRow[]) => {
        store.exportIds = selection.map(item => item.${codeConfig.rowKey}!)
      }

      return {
        /** 搜索 */
        onSearch,
        /** 表格选择change */
        onSelectionChange,
        ${
          refreshListHandlerStr ?
            `
          /** 刷新列表 */
          refreshListHandler,
        ` :
            ''
        }
        ${
          onExportExcelStr ?
            `
          /** 导出按钮事件 */
          onExportExcel,
        ` :
            ''
        }
        ${
          delActionHandlerStr ?
            `
              /** 删除操作按钮事件 */
              delActionHandler,
            ` :
            ''
        }
        ${
          editActionHandlerStr ?
            `
              /** 编辑操作按钮事件 */
              editActionHandler,
            ` :
            ''
        }
        ${
          onAddStr ?
            `
              /** 新增按钮事件 */
              onAdd,
            ` :
            ''
        }
        ${
          modifySubmitHandlerStr ?
            `
              /** 新增编辑提交事件 */
              modifySubmitHandler,
            ` :
            ''
        }
        ${
          onExportBeforeCreateStr ?
            `
              /** 导出前执行的方法 */
              onExportBeforeCreate,
            ` :
            ''
        }
      }
    }
  `
  utils.writeFile(path.join(codeConfig.modulePath, 'hooks', 'use-handler.ts'), code)
}
